<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.productId" clearable :placeholder="$t('tracibility.productId')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-if="false" v-model="listQuery.lineNumber" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" clearable @change="handleLineSelect">
        <el-option v-for="item in lineOptions" :key="item.lineNumber" :label="item.lineName" :value="item.lineNumber" />
      </el-select>
      <el-select v-model="listQuery.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable style="width: 350px">
        <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
      </el-select>
      <el-select v-model="listQuery.abnormalType" :placeholder="$t('abnormal.abnormalType')" class="filter-item" style="width: 150px">
        <el-option v-for="item in abnormalOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-date-picker v-model="listQuery.startTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.startDate')" class="filter-item" />
      <el-date-picker v-model="listQuery.endTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.endDate')" class="filter-item" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!-- <el-table-column :label="$t('common.seqNumber')" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.seqNumber }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('tracibility.productId')" width="220px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleCheckProcess(row)">{{ row.productId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('tracibility.productSn')" width="220px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleCheckProcess(row)">{{ row.part.productSn }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.lineNumber')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.processNumber')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('produce.typeNo')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.part.typeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.abnormalType')" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getAbornalType(row.abnormalType).color">{{ getAbornalType(row.abnormalType).label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.abnormalReason')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ '(' + row.defectCode + ')' + row.failReason }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('tracibility.testTime')" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" sortable="custom" prop="creatTime" width="220px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.creatTime }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column class-name="status-col" :label="$t('tracibility.processStatus')" width="180">
        <template slot-scope="{row}">
          <el-tag :type="row.part.processStatus==='OK'? 'success':'danger'">
            {{ row.part.processStatus }}
          </el-tag>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-row style="background:#fff;margin-bottom:32px;">
      <nightingale-Chart :chart-data="chartData" />
    </el-row>
  </div>
</template>

<script>
import { getLineList, getProcessList } from '@/api/equipment'
import { getAbnormalList, getAbnormalReasonCount } from '@/api/rework'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import NightingaleChart from '@/components/Charts/NightingaleChart.vue'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'ReworkSummary',
  components: {
    Pagination,
    NightingaleChart },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      lineOptions: [],
      processOptions: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        productSn: '',
        productId: '',
        lineNumber: this.$store.getters.lineNumber,
        processNumber: '',
        abnormalType: 0,
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+test_time'
      },
      abnormalOptions: [{ label: 'all', key: 0, color: 'primary' },
        { label: i18n.t('rework.rework'), key: 1, color: 'danger' },
        { label: i18n.t('rework.scrap'), key: 2, color: 'danger' }],
      downloadLoading: false,
      chartData: [
        { value: 40, name: 'rose 1' },
        { value: 38, name: 'rose 2' },
        { value: 32, name: 'rose 3' },
        { value: 30, name: 'rose 4' },
        { value: 28, name: 'rose 5' },
        { value: 26, name: 'rose 6' },
        { value: 22, name: 'rose 7' },
        { value: 18, name: 'rose 8' }
      ]
    }
  },
  created() {
    this.handleLineSelect()
    this.getList()
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    getAbornalType(type) {
      var label
      this.abnormalOptions.forEach(e => {
        if (e.key === type) {
          label = e
          return
        }
      })
      return label
    },
    // 获取清单
    getList() {
      this.listLoading = true
      getAbnormalList(this.listQuery).then(response => {
        this.list = response.data.abnormalParts
        this.total = response.data.total
        this.listLoading = false
      })
      this.listLoading = true
      this.chartData = []
      getAbnormalReasonCount(this.listQuery).then(response => {
        response.data.fails.forEach(e => {
          this.chartData.push({ value: e.countNum, name: e.failReason })
        })
        this.listLoading = false
      })
    },
    // 获取线体清单
    getLineList() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        if (this.lineOptions.length > 0) this.listQuery.lineNumber = this.lineOptions[0].lineNumber
        this.processOptions = []
        this.handleLineSelect()
        this.listLoading = false
      })
    },
    handleLineSelect() {
      this.processOptions = []
      getProcessList(this.listQuery).then(response => {
        this.processOptions = response.data.processes
      })
    },
    // 查看工艺结果清单
    handleCheckProcess(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/tracibility/processSummary', query: { productId: ret.productId }})
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('tracibility.productId'),
          i18n.t('tracibility.productSn'),
          i18n.t('tracibility.testTime'),
          i18n.t('equipment.lineNumber'),
          i18n.t('equipment.stationNumber'),
          i18n.t('produce.typeNo'),
          i18n.t('rework.abnormalReason')]
        const filterVal = ['productId', 'productSn', 'creatTime', 'lineNumber', 'stationNumber',
          'typeNo', 'failReason']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '异常清单' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'productSn' || j === 'typeNo') {
          return v.part[j]
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
